# -*- coding: utf-8 -*-
import os
import shutil
import tempfile
from datetime import datetime
import ctypes
import maya.cmds as cmds
import maya.mel as mel


class Check_Playblast ():
	def Check_Playblast(self, outputPath_Directory) :
		try:
			temp_folder = tempfile.gettempdir ()

			scenepath = cmds.file (q=1, sn=1)
			scenepathsp = scenepath.split ("/")
			scenename = scenepathsp[-1].split (".")[0]
			playblastTemp_folder = os.path.join (temp_folder, scenename).replace ("\\", "/")
			outputPath_Directory = os.path.join (outputPath_Directory, scenename + ".mov").replace ("\\", "/")
			fps = 0
			time_fps = cmds.currentUnit (q=1, t=1)
			if time_fps == "game" :
				fps = 15
			elif time_fps == "film" :
				fps = 24
			elif time_fps == "pal" :
				fps = 25
			elif time_fps == "ntsc" :
				fps = 30
			elif time_fps == "show" :
				fps = 48
			elif time_fps == "palf" :
				fps = 50
			elif time_fps == "ntscf" :
				fps = 60

			i = 1920
			width = 1920
			height = 804
			Fontsize = 40 * (width / i)
			Fontname = "\u9ed1\u4f53"
			PrimaryColour = "&H0000FFFF"
			SecondaryColour = "&H00FFFFFF"
			OutlineColour = "&HFFFFFFFF"
			BackColour = "&H00000000"
			BorderStyle = 1
			Outline = 0
			Shadow = 0

			assPath = os.path.join (playblastTemp_folder, scenename + ".ass").replace ("\\", "/")

			exportpath = os.path.join (playblastTemp_folder, scenename).replace ("\\", "/")

			inP = "-i " + exportpath + ".%04d.png"
			ffexe = "H:/RareWolf_Toolkit/Package/ffmpeg/ffmpeg.exe"

			list_headsUpDisplay = cmds.headsUpDisplay (listHeadsUpDisplays=1)
			if list_headsUpDisplay :
				for i in list_headsUpDisplay :
					cmds.headsUpDisplay (i, remove=True)
			ListCam = [i for i in cmds.listCameras (p = 1) if i != "persp"][0]
			if cmds.nodeType (ListCam) == "camera" :
				Old_Cam = cmds.listRelatives (ListCam , p = True)[0]
				print (Old_Cam)
			else :
				Old_Cam = ListCam
			print ("----------------------------------------------")
			print(Old_Cam)
			if not cmds.referenceQuery (Old_Cam , isNodeReferenced = True) :
				cmds.setAttr (Old_Cam + ".rnd" , 1)
				CameraShape = cmds.listRelatives (Old_Cam , shapes = 1)[0]
			print ("+++++++++++++++++++++++++++++++++")
			print (CameraShape)

			'''   
			all_camera = [i for i in cmds.listCameras (p=1) if i != "persp"]
			obj_list = []
			playblastCame = ""
			for i in all_camera :
				if not cmds.referenceQuery (i, isNodeReferenced=True) :
					obj_list.append (i)
					playblastCame = obj_list[0]
			for cam in cmds.ls (type="camera") :
				cmds.setAttr (cam + ".rnd", False)

			CameraShape = cmds.listRelatives (playblastCame, shapes=1)[0]
			cmds.setAttr (playblastCame + ".rnd", 1)
			'''
			cmds.colorManagementPrefs (e = True , cmEnabled = 1)
			cmds.colorManagementPrefs (edit = 1 , popupOnError = 1 , outputTarget = 'renderer' , outputTransformEnabled = 1 , outputTransformName = 'sRGB gamma')
			print("***********************************************************************************************************")

			cmds.setAttr ("hardwareRenderingGlobals.enableTextureMaxRes" , 1)
			cmds.setAttr ('hardwareRenderingGlobals.textureMaxResMode' , 1)
			cmds.setAttr ('hardwareRenderingGlobals.textureMaxResolution' , 1280)
			#cmds.evalDeferred('mel.eval ("AEReloadAllTextures")')
			#cmds.evalDeferred('mel.eval ("generateAllUvTilePreviews")')

			"""
			cmds.displayPref(displayGradient=True)
			cmds.setAttr ( 'hardwareRenderingGlobals.maxHardwareLights' , 4 )
			cmds.setAttr ( 'hardwareRenderingGlobals.enableTextureMaxRes' , 1 )
			cmds.setAttr ( 'hardwareRenderingGlobals.textureMaxResolution' , 1280 )
			cmds.setAttr ( 'hardwareRenderingGlobals.gammaValue ' , 50)
			"""

			exposure_adjustment = 2
			"""
			start_frame = cmds.getAttr ( "defaultRenderGlobals.startFrame" )
			end_frame = cmds.getAttr ( "defaultRenderGlobals.endFrame" )
			output_path = "E:/test/Cam_abc/"
	
	
			for frame in range ( int ( start_frame ) , int ( end_frame ) + 1 ) :
				cmds.currentTime ( frame )
	
				cmds.render ( output_path + "frame_%04d.jpg" % frame , x = 1920 , y = 1080 )
	
	
				cmds.displayRGBColor ( "perspShape" , 1.0 , 1.0 , 1.0 )  
				cmds.displayRGBColor ( "perspShape" , exposure_adjustment , exposure_adjustment , exposure_adjustment )  
			"""

			cmds.playblast (format="image", filename=exportpath, sequenceTime=0, clearCache=1, viewer=0, showOrnaments=1, fp=4, percent=100, compression="png", quality=100, widthHeight=(width, height), )
			hud_ass = ''
			hud_ass += "[Script Info]\n"
			hud_ass += "ScriptType: v4.00\n"
			hud_ass += "PlayResX: " + str (width) + "\n"
			hud_ass += "PlayResY: " + str (height) + "\n"
			hud_ass += "WrapStyle: 0\n"
			hud_ass += "[V4+ Styles]\n"
			hud_ass += "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n"
			hud_ass += u"Style: ProjSize,{},{},{},{},{},{},-1,0,0,0,60,60,0,0,{},{},{},8,0,0,5,134\n".format (str (Fontname), str (Fontsize), str (PrimaryColour), str (SecondaryColour), str (OutlineColour), str (BackColour), str (BorderStyle), str (Outline), str (Shadow))
			hud_ass += u"Style: Date,{},{},{},{},{},{},-1,0,0,0,60,60,0,0,{},{},{},7,10,0,5,134\n".format (str (Fontname), str (Fontsize), str (PrimaryColour), str (SecondaryColour), str (OutlineColour), str (BackColour), str (BorderStyle), str (Outline), str (Shadow))
			hud_ass += u"Style: FocalLength_text,{},{},{},{},{},{},-1,0,0,0,60,60,0,0,{},{},{},9,0,10,10,134\n".format (str (Fontname), str (Fontsize), str (PrimaryColour), str (SecondaryColour), str (OutlineColour), str (BackColour), str (BorderStyle), str (Outline), str (Shadow))
			hud_ass += u"Style: FileCam_text,{},{},{},{},{},{},-1,0,0,0,60,60,0,0,{},{},{},9,0,10,5,134\n".format (str (Fontname), str (Fontsize), str (PrimaryColour), str (SecondaryColour), str (OutlineColour), str (BackColour), str (BorderStyle), str (Outline), str (Shadow))
			hud_ass += u"Style: User,{},{},{},{},{},{},-1,0,0,0,60,60,0,0,{},{},{},1,10,0,5,134\n".format (str (Fontname), str (Fontsize), str (PrimaryColour), str (SecondaryColour), str (OutlineColour), str (BackColour), str (BorderStyle), str (Outline), str (Shadow))
			hud_ass += u"Style: PCName,{},{},{},{},{},{},-1,0,0,0,60,60,0,0,{},{},{},1,10,0,10,134\n".format (str (Fontname), str (Fontsize), str (PrimaryColour), str (SecondaryColour), str (OutlineColour), str (BackColour), str (BorderStyle), str (Outline), str (Shadow))
			hud_ass += u"Style: Scene_text,{},{},{},{},{},{},-1,0,0,0,60,60,0,0,{},{},{},2,0,0,5,134\n".format (str (Fontname), str (Fontsize), str (PrimaryColour), str (SecondaryColour), str (OutlineColour), str (BackColour), str (BorderStyle), str (Outline), str (Shadow))
			hud_ass += u"Style: TimeCode,{},{},{},{},{},{},-1,0,0,0,60,60,0,0,{},{},{},3,0,10,5,134\n".format (str (Fontname), str (Fontsize), str (PrimaryColour), str (SecondaryColour), str (OutlineColour), str (BackColour), str (BorderStyle), str (Outline), str (Shadow))
			hud_ass += u"Style: Frame_text,{},{},{},{},{},{},-1,0,0,0,60,60,0,0,{},{},{},3,0,10,10,134\n".format (str (Fontname), str (Fontsize), str (PrimaryColour), str (SecondaryColour), str (OutlineColour), str (BackColour), str (BorderStyle), str (Outline), str (Shadow))

			hud_ass += "\n"
			hud_ass += "[Events]\n"
			increase_value = round ((100 / float (fps)), 0)
			MinTimes = int (cmds.playbackOptions (q=1, minTime=1))
			MaxTimes = int (cmds.playbackOptions (q=1, maxTime=1))
			File_sceneName = cmds.file (q=1, sceneName=1, shortName=1)

			PCName = os.environ.get ("COMPUTERNAME")
			hud_resolution = (
					str (cmds.getAttr ("defaultResolution.width")) + " x " + str (cmds.getAttr ("defaultResolution.height")))

			frameRate = int (MaxTimes + 1 - MinTimes)

			now = datetime.now ()
			time = now.strftime ("%Y/%m/%d %H:%M:%S")
			for i in range (frameRate) :
				current_ms = str (((i + 1) % fps)).zfill (2)
				current_sencond = str ((i + 1) / fps).split (".")[0]
				current_timeconde = current_sencond + ":" + current_ms
				CameFocalLength = cmds.getAttr (CameraShape + ".focalLength", time=MinTimes + i)
				hud_ass += self.wirte_ass_file (i, increase_value, Old_Cam, hud_resolution, CameFocalLength, PCName, time, File_sceneName, current_timeconde, fps, MinTimes, MaxTimes, )
			with open (assPath, "w") as f :
				f.write (hud_ass.encode ("utf-8"))
				f.close ()

			audioOffset = 0
			audioFileCmd = ""
			AudioList = []

			Audios = cmds.ls (type="audio")
			aPlayBackSliderPython = mel.eval ("$tmpVar=$gPlayBackSlider")

			PlayBlastAudio = cmds.timeControl (aPlayBackSliderPython, q=1, s=1)
			if PlayBlastAudio :
				AudioList.append (PlayBlastAudio)
			if len (Audios) == 1 :
				if len (AudioList) == 1 :
					Audio = AudioList[0]
					audioOffset = int (cmds.getAttr (Audio + ".offset") - MinTimes)
					audioFile = cmds.sound (Audio, q=1, file=1)
				else :
					Audio = Audios[0]
					audioOffset = int (cmds.getAttr (Audio + ".offset") - MinTimes)
					audioFile = cmds.sound (Audio, q=1, file=1)
				print(audioFile)

				offsetSec = float (audioOffset) / float (fps)

				offsetCmd = ""
				if audioOffset > 0 :
					offsetCmd += "-itsoffset " + str (offsetSec) + " "
				else :
					offsetCmd += "-ss " + str (abs (offsetSec)) + " "

				if len (audioFile) or os.path.exists (audioFile) :
					audioFileCmd = offsetCmd + "-i " + audioFile
				if not os.path.isfile (audioFile) :
					audioFileCmd = ""
			timeRange = "-t " + str ((MaxTimes - MinTimes + 1) / float (fps))
			s = " "
			start = "-start_number" + " " + str (MinTimes)

			converted_path = assPath.replace ("/", "\\\\")
			converted_path = converted_path.replace (":", "\\:")
			assPaths = assPath.split ("/")
			assP = "-vf subtitles=" "\\'" + converted_path + "\\'"

			outP = ("-c:v libx264 -b 18000k -pix_fmt yuv420p -crf 1 -y " + outputPath_Directory)
			hudInfo = [start, inP, audioFileCmd, timeRange, assP, outP]

			command_line = ffexe + " " + s.join (hudInfo)

			os.popen (command_line)

			shutil.rmtree (playblastTemp_folder)
			return "YES"
		except Exception as e :
			return str(e)

	def is_ascii(self, string) :
		for char in string :
			if ord (char) > 127 :
				return False
		return True

	def getDisplayName(self) :
		GetUserNameEx = ctypes.windll.secur32.GetUserNameExW
		NameDisplay = 3
		size = ctypes.pointer (ctypes.c_ulong (0))
		GetUserNameEx (NameDisplay, None, size)
		nameBuffer = ctypes.create_unicode_buffer (size.contents.value)
		GetUserNameEx (NameDisplay, nameBuffer, size)
		computerName = os.popen ('hostname').read ()
		return (nameBuffer.value)

	def week_day(self) :
		now = datetime.now ()
		week = [u"星期一", u"星期二", u"星期三", u"星期四", u"星期五", u"星期六", u"星期日"]
		week_day = week[now.weekday ()]
		# utf8_week_day = week_day.encode('utf-8')
		time = now.strftime ('%Y/%m/%d %H:%M:%S')
		return (week_day)

	def wirte_ass_file(self, i, increase_value, playblastCame, hud_resolution, CameFocalLength, PCName, time, File_sceneName, current_timeconde, fps, MinTimes, MaxTimes) :
		hud_ass = ''
		hud_ass += u"Dialogue: 0,0:00:00.{},0:00:00.{},{},,0,0,0,,{}\n".format (str (round (i * increase_value, 0)), str (round (i * increase_value + increase_value, 0)), "Frame_text", str (MinTimes) + "/" + str (MinTimes + i) + "/" + str (MaxTimes))
		hud_ass += u"Dialogue: 0,0:00:00.{},0:00:00.{},{},,0,0,0,,{}\n".format (str (round (i * increase_value, 0)), str (round (i * increase_value + increase_value, 0)), "FileCam_text", str (playblastCame))
		hud_ass += u"Dialogue: 0,0:00:00.{},0:00:00.{},{},,0,0,0,,{}\n".format (str (round (i * increase_value, 0)), str (round (i * increase_value + increase_value, 0)), "ProjSize", hud_resolution)
		hud_ass += u"Dialogue: 0,0:00:00.{},0:00:00.{},{},,0,0,0,,{}\n".format (str (round (i * increase_value, 0)), str (round (i * increase_value + increase_value, 0)), "FocalLength_text", str (CameFocalLength))
		hud_ass += u"Dialogue: 0,0:00:00.{},0:00:00.{},{},,0,0,0,,{}\n".format (str (round (i * increase_value, 0)), str (round (i * increase_value + increase_value, 0)), "User", self.getDisplayName ())  # .encode("UTF-8")
		hud_ass += u"Dialogue: 0,0:00:00.{},0:00:00.{},{},,0,0,0,,{}\n".format (str (round (i * increase_value, 0)), str (round (i * increase_value + increase_value, 0)), "PCName", str (PCName))
		hud_ass += u"Dialogue: 0,0:00:00.{},0:00:00.{},{},,0,0,0,,{}\n".format (str (round (i * increase_value, 0)), str (round (i * increase_value + increase_value, 0)), "Date", str (time) + self.week_day ())
		hud_ass += u"Dialogue: 0,0:00:00.{},0:00:00.{},{},,0,0,0,,{}\n".format (str (round (i * increase_value, 0)), str (round (i * increase_value + increase_value, 0)), "Scene_text", str (File_sceneName))
		hud_ass += u"Dialogue: 0,0:00:00.{},0:00:00.{},{},,0,0,0,,{}\n".format (str (round (i * increase_value, 0)), str (round (i * increase_value + increase_value, 0)), "TimeCode", current_timeconde + "(" + str (fps) + "fps)")
		return (hud_ass)